from django.contrib.auth.models import Group, User

# from main.apps.common_filter.mixins import CommonFilterStatisticsMixin
from main.common.perm import perms
from main.common.perm.perms_config import PERMS_CONFIG
from main.mixins.mixins import OperatorMixins
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.views import APIView

from . import filters, serializers


class RoleViewSet(
    OperatorMixins,
    viewsets.ModelViewSet,
):
    """
    角色管理
    """

    filter_class = filters.RoleFilter
    queryset = Group.objects.filter(delete_time__isnull=True)
    serializer_class = serializers.RoleSerializer
    ordering = ("-id",)
    search_fields = (
        "name",
        "id",
    )

    def get_permissions(self):
        if self.action == "list":
            self.permission_classes = (perms.PermsRequired("main.check_user_group"),)
        elif self.action == "create":
            self.permission_classes = (perms.PermsRequired("main.add_user_group"),)
        elif self.action in ("update", "partial_update"):
            self.permission_classes = (perms.PermsRequired("main.edit_user_group"),)
        elif self.action == "destroy":
            self.permission_classes = (perms.PermsRequired("main.edit_user_group"),)

        return super(RoleViewSet, self).get_permissions()

    def get_serializer_class(self):
        if self.action in ("create",):
            return serializers.EmbedGroupSerializer
        if self.action == "get_role_options":
            return serializers.EmbedGroupSerializer
        if self.action in ("set_perms", "update", "partial_update"):
            return serializers.EditRoleSerializer
        return self.serializer_class

    @action(methods=["get"], detail=False)
    def get_role_options(self, request, *args, **kwargs):
        request.GET._mutable = True
        request.GET["page_size"] = 1000
        request.GET["page"] = 1
        request.GET._mutable = False
        return self.list(request, *args, **kwargs)

    @action(methods=["put"], detail=True)
    def set_perms(self, request, pk, *args, **kwargs):
        """set_perms"""
        return super().update(request, pk, *args, **kwargs)


class RolePermsConfig(APIView):
    """
    权限显示配置
    """

    def get(self, request, format=None):
        return Response(PERMS_CONFIG)


class UserViewSet(
    OperatorMixins,
    viewsets.ModelViewSet,
):
    """用户管理"""

    common_filter_app_name = "userviewset"

    queryset = User.objects.filter(delete_time__isnull=True).prefetch_related("groups")
    serializer_class = serializers.UserSerializer
    ordering = ("-id",)
    filter_class = filters.UserFilter

    search_fields = ("id", "username", "first_name")

    def get_permissions(self):
        if self.action == "list":
            self.permission_classes = (perms.PermsRequired("main.check_user_list"),)
        elif self.action in ["assign_role", "update", "partial_update", "create"]:
            self.permission_classes = (perms.PermsRequired("main.edit_user_list"),)

        return super(UserViewSet, self).get_permissions()

    def get_serializer(self, *args, **kwargs):
        if self.action == "assign_role":
            self.serializer_class = serializers.AssignUserRoleSerializer
        if self.action in ["update", "partial_update", "create"]:
            self.serializer_class = serializers.EditUserSerializer
        return super(UserViewSet, self).get_serializer(*args, **kwargs)

    @action(methods=["post"], detail=False)
    def assign_role(self, request):
        """批量分配角色"""
        res_data = self.get_serializer().run_validation(request.data)
        return Response(res_data)
